<?php
/**
 * @copyright 码小象 www.uxphp.com
 * www.yxxhui.com
 * www.mxxiang.com
 * www.mxxiang.cn
 * 自研正版源码，赋能开发者
 */

namespace app\services\care;


use app\dao\care\WechatFanDao;
use app\model\care\WechatFan;
use app\model\wechat\WechatUser;
use app\services\BaseServices;

class WechatFanServices extends BaseServices
{
    public function __construct(WechatFanDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * 列表
     * @param array $where
     * @param bool $is_page
     * @return array
     */
    public function getList(array $where,bool $is_page = false){
        $page = $limit = 0;
        if($is_page) [$page,$limit] = $this->getPageValue();
        $list = $this->dao->getList($where,$page,$limit,$is_page);
        $sex = [
            0 => '未知',
            1 => '男',
            2 => '女'
        ];
        foreach ($list['list'] as &$item){
            $item['subscribe'] = $item['subscribe'] == 1 ? '是' : '否';
            $item['subscribe_time'] = $item['subscribe_time'] ? date('Y-m-d H:i',$item['subscribe_time']) : '暂无';
            $item['sex'] = $sex[$item['sex']];
        }
        return $list;
    }

    /**
     * 同步粉丝列表
     * @param $data
     * @return \think\Collection
     * @throws \Exception
     */
    public function getFansSync($data){
        $res = app()->make(WechatFan::class)->saveAll($data);
        return $res;
    }

    /**
     * 通过UID获取公众号openid
     * @param $uid
     * @return false|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getWechatOpenid($uid){
        $user = WechatUser::where('uid',$uid)->find();
        if(!$user) return false;
        $user = $user->toArray();
        $wechat = WechatFan::where('unionid',$user['unionid'])->find();
        if(!$wechat) return false;
        $wechat = $wechat->toArray();
        return $wechat['wechat_openid'];
    }
}